/*
 * @lc app=leetcode.cn id=515 lang=cpp
 *
 * [515] 在每个树行中找最大值
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    vector<int> largestValues(TreeNode* root) {
        //同理用dfs，附带传递当前行数
        dfs(root, 0);
        for(int i = 0; i < hash.size(); i++)
            ans.push_back(hash[i]);
        return ans;
    }
private:
    unordered_map<int, int> hash;
    vector<int> ans;
    void dfs(TreeNode* t, int level){
        if(t == nullptr) return;
        if(hash.count(level) == 0){
            hash[level] = t->val;
        }
        else{
            hash[level] = max(hash[level], t->val);
        }
        dfs(t->left, level + 1);
        dfs(t->right, level + 1);
        return;
    }
};
// @lc code=end

